import { Button, Cascader, DatePicker, Form, Input, Picker, SafeArea, Toast } from 'antd-mobile'
import { AddCircleOutline, CloseCircleFill } from 'antd-mobile-icons'
import dayjs from 'dayjs'
import { useEffect, useRef, useState } from 'react'
import styles from './index.module.less'
import { getData, postData, postFile, putData } from '@/servers/http'
import { api } from '@/servers/api'
import { history } from 'umi'
import { getCookie } from '@/storage'
import wx from 'weixin-webview-jssdk'

type fieldType = {
    label: string
    value: string
    children?: fieldType[]
}

const TrackInput = () => {
    // isRe：是否是从查看页的重新录入按钮进入 1-是；0-否
    const { id, group_id, isRe = 0, domain } = history.location.query || {}
    const [form] = Form.useForm()
    // 单位性质下拉
    const [unitList, setUnitList] = useState<fieldType[]>([])
    // 所在地区下拉
    const [regionList, setRegionList] = useState([])
    // 行业下拉
    const [industryList, setIndustryList] = useState<fieldType[]>([])
    // 附件材料列表
    const [fileList, setFileList] = useState<any[]>([])
    const fileRef = useRef<any>(null)

    /** 获取详情 */
    const getDetail = () => {
        if (!Number(id) || Number(isRe)) return
        const params = { access_token: getCookie('MLHTOKEN'), domain }
        postData(`${api.employDetail}/${id}`, params).then(({ data }) => {
            const { entry_time, company_name, credit_code, company_type, province_code, city_code, area_code, parent_industry_id, industry_id, profession_name, salary, attachment_file } = data || {}
            form.setFieldsValue({
                entry_time: dayjs(entry_time).toDate(),
                company_name,
                credit_code,
                company_type: [String(company_type)],
                region: [province_code, city_code, area_code],
                industry: [Number(parent_industry_id), Number(industry_id)],
                profession_name,
                salary,
                attachment_file,
            })
            setFileList(attachment_file)
        })
    }
    /** 获取单位性质下拉 */
    const getUnitList = () => {
        getData(api.companyType).then(({ data }) => {
            const newArr = Object.keys(data).map(item => ({ label: data[item], value: item }))
            setUnitList(newArr)
        })
    }
    /** 获取所在地区下拉列表 */
    const getCityList = () => {
        getData(api.cityList).then(({ data }) => {
            setRegionList(data.regionData || [])
        })
    }
    /** 获取行业下拉列表 */
    const getIndustryList = () => {
        getData(api.industryList).then(({ data }) => {
            setIndustryList(data || [])
        })
    }
    useEffect(() => {
        document.title = '录入'
        getDetail()
        getUnitList()
        getCityList()
        getIndustryList()
    }, [])
    /** 上传文件 */
    const upLoadImage = (e: any) => {
        if (e.target?.files?.length > 0) {
            if (e.target.files.length + fileList.length > 5) {
                Toast.show('最多上传五份文件')
                return
            }
            /** 是否超过10MB */
            let isExceed10MB = false
            e.target.files.forEach((file: File) => {
                if (file.size > 1024 * 1024 * 10) {
                    isExceed10MB = true
                    return
                }
            })
            if (isExceed10MB) {
                Toast.show('文件大小不得超过10MB')
                return
            }
            const promiseArr: any[] = []
            e.target?.files?.forEach((file: File) => {
                promiseArr.push(postFile(api.mlhUpload, { file, mlh_side_domain: domain }))
            })
            const toast = Toast.show({
                icon: 'loading',
                content: '上传中…',
                duration: 0,
            })
            Promise.allSettled(promiseArr)
                .then(res => {
                    const fileData: { url: string; name: string }[] = [...fileList]
                    res.forEach(item => {
                        if (item.status === 'fulfilled') {
                            const { filename, url } = item.value.data || {}
                            fileData.push({ url, name: filename })
                        }
                    })
                    setFileList(fileData)
                    form.setFieldValue('attachment_file', fileData)
                    toast.close()
                })
                .catch(() => {
                    toast.close()
                })
        }
    }
    /** 移除文件 */
    const removeFile = (url: string) => {
        const newArr = fileList.filter(item => item.url !== url)
        setFileList(newArr)
        form.setFieldValue('attachment_file', newArr)
    }
    /** 提交保存 */
    const handleOk = () => {
        form.validateFields().then(async values => {
            const { entry_time, company_type, region, industry } = values || {}
            const parent = industryList.find(item => item.value === industry[0])
            const self = parent?.children?.find(item => item.value === industry[1])
            const params = {
                ...values,
                access_token: getCookie('MLHTOKEN'),
                domain,
                gid: group_id,
                entry_time: dayjs(entry_time).format('YYYY-MM-DD'),
                company_type: company_type[0],
                province_code: region[0],
                city_code: region[1],
                area_code: region[2],
                parent_industry_id: industry[0],
                parent_industry_name: parent?.label,
                industry_id: industry[1],
                industry_name: self?.label,
            }
            let res
            if (Number(id)) {
                res = await putData(`${api.submitEmploys}/${id}`, params)
            } else {
                res = await postData(api.submitEmploys, params)
            }
            if (res.data) {
                Toast.show({
                    icon: 'success',
                    content: Number(id) ? '编辑成功' : '录入成功',
                })
                wx.miniProgram.navigateBack()
            }
        })
    }

    return (
        <div className={styles.track_input}>
            <Form form={form} layout="horizontal" className={styles.form_box}>
                <Form.Item
                    label="入职时间"
                    name="entry_time"
                    trigger="onConfirm"
                    rules={[{ required: true }]}
                    onClick={(e, pickerRef) => {
                        pickerRef.current?.open()
                    }}
                >
                    <DatePicker>{value => (value ? dayjs(value).format('YYYY-MM-DD') : <span className={styles.placeholder_text}>请选择</span>)}</DatePicker>
                </Form.Item>
                <Form.Header>
                    <div />
                </Form.Header>
                <Form.Item label="单位名称" name="company_name" rules={[{ required: true }]}>
                    <Input placeholder="请输入" maxLength={50} />
                </Form.Item>
                <Form.Item label="统一信用代码" name="credit_code">
                    <Input placeholder="请输入" maxLength={18} onKeyUp={(e: any) => (e.target.value = e.target.value.replace(/[^\w\.\/]/gi, ''))} />
                </Form.Item>
                <Form.Item
                    label="单位性质"
                    name="company_type"
                    trigger="onConfirm"
                    rules={[{ required: true }]}
                    onClick={(e, pickerRef) => {
                        pickerRef.current?.open()
                    }}
                >
                    <Picker columns={[unitList]}>
                        {value => {
                            return value[0] ? value[0].label : <span className={styles.placeholder_text}>请选择</span>
                        }}
                    </Picker>
                </Form.Item>
                <Form.Item
                    label="所在地"
                    name="region"
                    trigger="onConfirm"
                    rules={[{ required: true }]}
                    onClick={(e, cascaderRef) => {
                        cascaderRef.current?.open()
                    }}
                >
                    <Cascader options={regionList}>
                        {items => {
                            return items.every(item => item === null) ? <span className={styles.placeholder_text}>请选择</span> : items.map(item => item?.label ?? '未选择').join('-')
                        }}
                    </Cascader>
                </Form.Item>
                <Form.Item
                    label="行业"
                    name="industry"
                    trigger="onConfirm"
                    rules={[{ required: true }]}
                    onClick={(e, pickerRef) => {
                        pickerRef.current?.open()
                    }}
                >
                    <Cascader options={industryList}>
                        {items => {
                            return items.every(item => item === null) ? <span className={styles.placeholder_text}>请选择</span> : items.map(item => item?.label ?? '未选择').join('/')
                        }}
                    </Cascader>
                </Form.Item>
                <Form.Header>
                    <div />
                </Form.Header>
                <Form.Item label="岗位名称" name="profession_name">
                    <Input placeholder="请输入" maxLength={50} />
                </Form.Item>
                <Form.Item label="月薪" name="salary" rules={[{ required: true }]} extra={<span className={styles.unit}>元</span>}>
                    <Input placeholder="请输入" type="number" min={1} max={99999998} />
                </Form.Item>
                <Form.Header>
                    <div />
                </Form.Header>
                <Form.Item label="附件材料" name="fake_field" childElementPosition="right">
                    <AddCircleOutline color="rgba(23,26,29,0.4)" fontSize={24} onClick={() => fileRef.current?.click()} />
                    <input ref={fileRef} type="file" accept="image/*" multiple onChange={upLoadImage} style={{ display: 'none', cursor: 'pointer' }} />
                </Form.Item>
                <Form.Item name="attachment_file">
                    <div className={styles.credit_box}>
                        <p className={styles.extra_title}>请上传可证明入职的附件材料，例如劳动合同、社保记录、工牌照片等；支持上传jpe、jpeg、png格式图片，大小不超过10MB，最多可上传5张</p>
                        <div className={styles.file_box}>
                            {fileList.map(item => {
                                const { url } = item || {}
                                return (
                                    <div className={styles.file_item} key={url}>
                                        <img src={url} />
                                        <CloseCircleFill className={styles.remove_icon} onClick={() => removeFile(url)} />
                                    </div>
                                )
                            })}
                        </div>
                    </div>
                </Form.Item>
            </Form>
            <SafeArea position="bottom" />
            <div className={styles.footer_box}>
                <Button className={styles.btn} onClick={handleOk}>
                    保存
                </Button>
                <SafeArea position="bottom" />
            </div>
        </div>
    )
}

export default TrackInput
